package com.cfh.web.json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.util.Assert;

import com.cfh.ahead.Constant;
import com.cfh.domain.Config;
import com.cfh.domain.ConfigExample;
import com.cfh.domain.ConfigKey;
import com.cfh.domain.ConfigExample.Criteria;
import com.cfh.service.ConfigService;
import com.cfh.util.Tools;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class ConfigJson extends ActionSupport implements ModelDriven {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ConfigJson.class);
	
	private static final long serialVersionUID = 1L;
	private ConfigService configService;
	private Map root = new HashMap();
	private Config Config = new Config();
	private String[] idsToDel = new String[200];
	private String CFG_VALUE_REAL;
	private String CFG_FREETEXT3_REAL;
	private String CFG_FREETEXT1_REAL;
	public ConfigJson() {
		super();

	}
	private int start;
	private int limit;
	private String sort;
	private String dir;
	
	private String SERACH_CODE;
	private String SERACH_TYPE;

	/***
	 * 得到所有用户
	 */
	public String list() {
		String encoding = ServletActionContext.getRequest().getCharacterEncoding();
		logger.debug("list()"); //$NON-NLS-1$
		
		ConfigExample example = new ConfigExample();
		Criteria crit = example.createCriteria();
		example.setOrderByClause(buildOrderString());
		if(Tools.hasText(SERACH_TYPE)){
			logger.debug("list()"); //$NON-NLS-1$
			crit.andCFG_TYPELike("%"+SERACH_TYPE+"%");
		}
		
		if(Tools.hasText(SERACH_CODE)){
			logger.debug("list()"); //$NON-NLS-1$
			crit.andCFG_CODELike("%"+SERACH_CODE+"%");
		}
		//add more search 
		
		List list = configService.selectByExample(example, start, limit);
		//int count = configService.countByExample(example);
		
		int count = 0;
		try {
			count = configService.countByExample(example);
		} catch (Exception e) {
			count = Constant.MAX_COUNT_WHEN_EXCEPTION;
			logger.warn("list()", e); //$NON-NLS-1$
		}
		
		if(Tools.hasText(SERACH_TYPE)){
			configService.selectMoreFields(list, SERACH_TYPE);
		}
		root.put("total", new Integer(count));
		root.put("items", list);
		return SUCCESS;
	}

	

	public String add() {
		logger.debug("add() - add() start"); //$NON-NLS-1$
		try {
			
			Assert.isTrue(Config != null);
			unescape( Config);
			try {
				Config.setCFG_TYPE(Config.getCFG_TYPE().toUpperCase());
			} catch (Exception e) {
				e.printStackTrace();
			}

			if (Config.getCFG_TYPE() != null) {
				if (Config.getCFG_TYPE().equals(Constant.CFG_TYPE_PDF) || Config.getCFG_TYPE().equals(Constant.CFG_TYPE_BUYURL)
						|| Config.getCFG_TYPE().equals(Constant.CFG_TYPE_INTRO)) {					
					genIdType1(Config);
				}else if(Config.getCFG_TYPE().equals(Constant.CFG_TYPE_FLV)){
					genIdType2(Config);
				}
			}

			configService.insert(Config);
			root.put("success", new Boolean(true));
			logger.debug("add() - add() end"); //$NON-NLS-1$
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			logger.warn("add()", e); //$NON-NLS-1$
			root.put("success", new Boolean(false));
			root.put("msg", "可能是主键冲突");
			return SUCCESS;
		}
	}

	private void unescape(Config c) {
		c.setCFG_VALUE(Tools.unescapeTwice(CFG_VALUE_REAL));
		c.setCFG_FREETEXT3(Tools.unescapeTwice(CFG_FREETEXT3_REAL));
		c.setCFG_FREETEXT1(Tools.unescapeTwice(CFG_FREETEXT1_REAL));
	}



	private void genIdType2(Config config2) {
		if (config2.getMM_LANG() != null && config2.getMM_PRODUCT() != null) {
			config2.setCFG_CODE(config2.getMM_PRODUCT() + Constant.CHAR_ + config2.getMM_LANG());
		}
		
	}

	private void genIdType1(Config config2) {
		if (config2.getMM_LANG() != null && config2.getMM_PRODUCT() != null && config2.getMM_COMPANY() != null) {
			config2.setCFG_CODE(config2.getMM_PRODUCT() + Constant.CHAR_ + config2.getMM_COMPANY() + Constant.CHAR_ + config2.getMM_LANG());
		}
	}



	public String modify() {
		try {
			logger.debug("modify()"); //$NON-NLS-1$
			Assert.notNull(Config);
			unescape(Config);
			int i = configService.update(Config);
			if (i > 0) {
				root.put("success", new Boolean(true));
			} else {
				root.put("success", new Boolean(false));
			}
			logger.debug("modify() - modify() end"); //$NON-NLS-1$
			return SUCCESS;

		} catch (Exception e) {
			e.printStackTrace();
			logger.warn("modify()", e); //$NON-NLS-1$
			root.put("success", new Boolean(false));
			return SUCCESS;
		}
	}

	public String del() {
		logger.debug("del() - del() start"); //$NON-NLS-1$
		ConfigExample example = new ConfigExample();
		Criteria criteria = example.createCriteria();
		int count = 0;
		ConfigKey key = null;
		List idList = new ArrayList();
		for (int i = 0; i < idsToDel.length; i++) {
			if (idsToDel[i] != null) {
				String[] arry = idsToDel[i].split("\\^T");
				Assert.isTrue(arry != null && arry.length == 2,
						"config key has two");
				key = new ConfigKey();
				key.setCFG_CODE(arry[0]);
				key.setCFG_TYPE(arry[1]);
				int countcicle = configService.deleteByPrimaryKey(key);
				count +=countcicle;
			}
		}
		root.put("success", new Boolean(true));
		root.put("count", new Integer(count));
		logger.debug("del() - del() end"); //$NON-NLS-1$
		return SUCCESS;
	}

	private String buildOrderString() {
		String toReturn = null;
		if (Tools.hasText(sort)) {
			toReturn = sort;
			if (Tools.hasText(dir)) {
				toReturn += " " + dir;
			}
		}
		return toReturn;
	}

	/***
	 * nouse
	 */
	public String execute() {

		return SUCCESS;
	}

	public Map getRoot() {
		return root;
	}

	
	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getLimit() {
		return limit;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getStart() {
		return start;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getSort() {
		return sort;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getDir() {
		return dir;
	}

	public Object getModel() {

		return Config;
	}

	public void setIdsToDel(String[] idsToDel) {
		this.idsToDel = idsToDel;
	}

	public String[] getIdsToDel() {
		return idsToDel;
	}



	public void setConfigService(ConfigService ConfigService) {
		this.configService = ConfigService;
	}



	public ConfigService getConfigService() {
		return configService;
	}



	public void setSERACH_CODE(String sERACH_CODE) {
		SERACH_CODE = sERACH_CODE;
	}



	public String getSERACH_CODE() {
		return SERACH_CODE;
	}



	public void setSERACH_TYPE(String sERACH_TYPE) {
		SERACH_TYPE = sERACH_TYPE;
	}



	public String getSERACH_TYPE() {
		return SERACH_TYPE;
	}



	public void setCFG_VALUE_REAL(String cFG_VALUE_REAL) {
		CFG_VALUE_REAL = cFG_VALUE_REAL;
	}



	public String getCFG_VALUE_REAL() {
		return CFG_VALUE_REAL;
	}



	public void setCFG_FREETEXT3_REAL(String cFG_FREETEXT3_REAL) {
		CFG_FREETEXT3_REAL = cFG_FREETEXT3_REAL;
	}



	public String getCFG_FREETEXT3_REAL() {
		return CFG_FREETEXT3_REAL;
	}



	public void setCFG_FREETEXT1_REAL(String cFG_FREETEXT1_REAL) {
		CFG_FREETEXT1_REAL = cFG_FREETEXT1_REAL;
	}



	public String getCFG_FREETEXT1_REAL() {
		return CFG_FREETEXT1_REAL;
	}

}
